package com.leyou.search.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.leyou.item.pojo.*;
import com.leyou.search.client.BrandClient;
import com.leyou.search.client.CategoryClient;
import com.leyou.search.client.GoodsClient;
import com.leyou.search.client.SpecificationClient;
import com.leyou.search.pojo.Goods;
import com.leyou.search.repository.GoodsRepository;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

@Service
public class ImportService {
    @Autowired
    private CategoryClient categoryClient;

    @Autowired
    private SpecificationClient specificationClient;

    @Autowired
    private GoodsRepository goodsRepository;

    @Autowired
    private BrandClient brandClient;

    @Autowired
    private GoodsClient goodsClient;

    @Autowired
    private ObjectMapper mapper;

    //封装Goods
    public Goods buildGoods(Spu spu) throws IOException {
        //获取分类数据
        List<String> cnames = categoryClient.queryNamesByIds(Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));
        //获得品牌数据
        Brand brand = brandClient.queryBrandById(spu.getBrandId());
        //获得spu下的skus数据
        List<Sku> skus = goodsClient.querySkusBySpuId(spu.getId());
        //获得所有搜索的规格参数
        List<SpecParam> params = specificationClient.querySpecParams(null, spu.getCid3(), true, null);
        //查询spuDetail
        SpuDetail spuDetail = goodsClient.querySpuDetailBySpuId(spu.getId());


        //处理sku中的数据,仅封装id、价格、标题、图片，并获得价格集合
        Set<Long> prices = new HashSet<>();
        List<Map<String,Object>> skuList=new ArrayList<>();
        skus.forEach(sku -> {
            prices.add(sku.getPrice());

            Map<String,Object> map=new HashMap<>();
            map.put("id",sku.getId());
            map.put("title",sku.getTitle());
            map.put("price",sku.getPrice());
            map.put("image", StringUtils.isBlank(sku.getImages())? "": StringUtils.split(sku.getImages(),",")[0]);
            skuList.add(map);
        });


        //处理规格参数
        //获得spuDetail中的通用规格参数
        Map<String,Object> genericSpec =mapper.readValue(spuDetail.getGenericSpec(),new TypeReference<Map<String,Object>>(){});
        //获得spuDetail中的通用特有参数
        Map<String,List<Object>> specialSpec =mapper.readValue(spuDetail.getSpecialSpec(),new TypeReference<Map<String,List<Object>>>(){});

        Map<String,Object> searchMap=new HashMap<>();
        params.forEach(param -> {
            if(param.getGeneric()){
                //通用规格参数
                String value = genericSpec.get(param.getId().toString()).toString();
                if(param.getNumeric()){
                    value=chooseSegment(value,param);
                }
                searchMap.put(param.getName(),StringUtils.isBlank(value) ? "其它" : value);
            }else {
                //特殊规格参数
                //String value = specialSpec.get(param.getId().toString()).toString();
                List<Object> value=specialSpec.get(param.getId().toString());

                searchMap.put(param.getName(),value);
            }
        });

        //封装Goods
        Goods goods=new Goods();

        goods.setId(spu.getId());
        goods.setSubTitle(spu.getSubTitle());
        goods.setCid1(spu.getCid1());
        goods.setCid2(spu.getCid2());
        goods.setCid3(spu.getCid3());
        goods.setBrandId(spu.getBrandId());
        goods.setCreateTime(spu.getCreateTime());
        //商品的标题,分类,品牌
        goods.setAll(spu.getTitle()+" "+StringUtils.join(cnames," ")+" "+brand.getName());
        //sku中所有价格的集合,方便以价格进行搜索
        goods.setPrice(prices);
        //spu中的所有skus
        goods.setSkus(mapper.writeValueAsString(skuList));
        //搜索的规格参数
        goods.setSpecs(searchMap);

        return goods;
    }

    //处理规格参数
    private String chooseSegment(String value, SpecParam p) {
        double val = NumberUtils.toDouble(value);
        String result = "其它";
        // 保存数值段
        for (String segment : p.getSegments().split(",")) {
            String[] segs = segment.split("-");
            // 获取数值范围
            double begin = NumberUtils.toDouble(segs[0]);
            double end = Double.MAX_VALUE;
            if (segs.length == 2) {
                end = NumberUtils.toDouble(segs[1]);
            }
            // 判断是否在范围内
            if (val >= begin && val < end) {
                if (segs.length == 1) {
                    result = segs[0] + p.getUnit() + "以上";
                } else if (begin == 0) {
                    result = segs[1] + p.getUnit() + "以下";
                } else {
                    result = segment + p.getUnit();
                }
                break;
            }
        }
        return result;
    }
}
